package com.hsxc.cdz.monitor.codec;

import java.util.List;

import com.hsxc.cdz.base.util.BytesUtil;
import com.hsxc.cdz.monitor.bean.MessageNew;
import com.hsxc.cdz.monitor.bean.second.HeartPileMsg;
import com.hsxc.cdz.monitor.bean.second.SecMessage;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 刘力文 对读取的数据进行解码
 */
public class MyDecoder extends ByteToMessageDecoder {

    private Logger logger = LoggerFactory.getLogger(MyEncoder.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {

        logger.info(in.readableBytes() + "");
        if (in.readableBytes() < 18) {
            return;
        }
        in.markReaderIndex();
        byte start = in.readByte();
        if (start == 0xfe) { // 直流桩协议
            byte[] blength = new byte[2];
            in.readBytes(blength);
            int clength = BytesUtil.bytesToIntDesc(blength);
            if (in.readableBytes() >= clength) {
                byte[] content = new byte[clength];
                in.readBytes(content);
                SecMessage result = transMessage(content);
                if (result != null) {
                    out.add(result);
                }
            } else {
                in.resetReaderIndex();
            }
        } else { // 交流桩协议
            in.resetReaderIndex();
            if (in.readableBytes() >= 29) {
                byte[] result1 = new byte[29];
                in.markReaderIndex();
                in.readBytes(result1);
                //in.markReaderIndex();
                MessageNew message = new MessageNew();
                message.getMessageFromByte(result1);
                logger.info(message.toString());
                int length = message.getContentLength();
                if (in.readableBytes() >= length) {
                    byte[] result2 = new byte[length];
                    in.readBytes(result2);
                    //in.markReaderIndex();
                    message.setContent(result2);
                    logger.info("解码--" + MyEncoder.byte2hex(result1) + "分隔符" + MyEncoder.byte2hex(result2));
                    out.add(message);
                }

            }

        }
    }

    // 生成直流桩消息体
    public SecMessage transMessage(byte[] data) {
        byte frame = data[13];
        switch (frame) {
            case 5: // 心跳
                if (data.length == HeartPileMsg.length) {
                    return new HeartPileMsg(data);
                }
                break;
            case 9: // 交易账单
                break;
            case 21: // 开始充电
                break;
        }

        return null;
    }

}
